package cn.mazexal;

import cn.hutool.core.util.IdUtil;
import cn.mazexal.dao.ExamDao;
import cn.mazexal.dbModel.ExamQuestionRelationshipDO;
import cn.mazexal.dbModel.QuestionTagDO;
import cn.mazexal.dbModel.TagDO;
import cn.mazexal.excelModel.QuestionExcel;
import cn.mazexal.excelModel.QuestionListener;
import cn.mazexal.tools.DaoUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.*;

/**
 * @author: Mazexal
 * Date: 2025/5/18
 */
public class BatchAddQuestionByExcel {

    public static void main(String[] args) throws Exception {
        SqlSession session = DaoUtil.getSession();
        ExamDao examDao = session.getMapper(ExamDao.class);
        // 读取excel
        String filePath = "F:\\workHome3\\examTools\\doc\\tmp\\questions.xls";
        List<QuestionExcel> res = EasyExcel.read(filePath, QuestionExcel.class, new QuestionListener())
                .sheet("Sheet1")  // 指定Sheet名称
                .doReadSync();
        res.forEach(i -> i.setId(IdUtil.getSnowflakeNextId()));

        for (QuestionExcel re : res) {
            // 检查答案格式是否正确
            if (re.getQuestionType().equals("1") || re.getQuestionType().equals("2")) {
                boolean answerCheck = checkAnswer(re.getAnswer());
                if (!answerCheck) {
                    System.err.println(re.getContext() + "答案格式错误：" + re.getAnswer());
                    return;
                }
            }
        }

        // 检查examID;
        String examId = res.get(0).getExamId();
        if (examDao.getExamById(examId) == null) {
            System.err.println("examId不存在");
            return;
        }
        for (QuestionExcel re : res) {
            re.setId(IdUtil.getSnowflakeNextId());
        }
        examDao.insertBatch(res);
        for (QuestionExcel item : res) {
            handlerTags(item, examDao);
        }
        // 处理
        List<ExamQuestionRelationshipDO> relationshipDOList = new ArrayList<>();
        for (QuestionExcel item : res) {
            ExamQuestionRelationshipDO relationshipDO = new ExamQuestionRelationshipDO();
            relationshipDO.setId(IdUtil.getSnowflakeNextId());
            relationshipDO.setQuestionId(item.getId());
            relationshipDO.setExamId(Long.valueOf(examId));
            relationshipDO.setSortNum(Integer.valueOf(item.getSortNum()));
            relationshipDOList.add(relationshipDO);
        }
        examDao.insertBatchRelationship(relationshipDOList);

        System.out.println("finish");
    }

    private static boolean checkAnswer(String input) {
        if (StringUtils.isEmpty(input)) {
            return false;
        }
        input = input.trim();
        if (input.length() == 1) {
            // 检查是否是大写英文字母
            return input.matches("[A-Z]");
        }
        if (input.length() > 0) {
            String[] arr = input.split(",");
            if (arr.length == 1) {
                return false;
            }
            for (String s : arr) {
                if (!s.matches("[A-Z]")) {
                    return false;
                }
            }
        }
        return true;
    }


    public static void handlerTags(QuestionExcel questionVO, ExamDao examDao) {
        if (StringUtils.isNotBlank(questionVO.getTagNames())) {
            Long examBankId = questionVO.getExamBankId();
            String[] tags = questionVO.getTagNames().split(",");
            Set<String> tagSet = new HashSet<>();
            for (String tag : tags) {
                tagSet.add(tag);
            }
            List<TagDO> tagList = examDao.getTagByNames(Arrays.asList(tags), examBankId);
            if (CollectionUtils.isEmpty(tagList)) {
                // 防止返回null，这里返回一个空list
                tagList = new ArrayList<>();
            }
            if (tagList.size() != tags.length) {
                List<TagDO> tagListForInsert = new ArrayList<>();
                for (TagDO tagDO : tagList) {
                    tagSet.remove(tagDO.getTagName());
                }
                for (String tagName : tagSet) {
                    TagDO tagDO = new TagDO();
                    tagDO.setTagName(tagName);
                    tagDO.setExamBankId(examBankId);
                    tagListForInsert.add(tagDO);
                }
                if (CollectionUtils.isNotEmpty(tagListForInsert)) {
                    examDao.batchInsertTags(tagListForInsert);
                }
            }
            // 第二次读取, 应该是能全部获取到了
            tagList = examDao.getTagByNames(Arrays.asList(tags), examBankId);
            // 先清空所有的tag关联
            examDao.deleteByQuestionId(questionVO.getId(), examBankId);
            List<QuestionTagDO> questionTagDOList = new ArrayList<>();
            for (TagDO tagDO : tagList) {
                QuestionTagDO questionTagDO = new QuestionTagDO();
                questionTagDO.setId(IdUtil.getSnowflakeNextId());
                questionTagDO.setQuestionId(questionVO.getId());
                questionTagDO.setTagId(tagDO.getId());
                questionTagDO.setExamBankId(examBankId);
                questionTagDOList.add(questionTagDO);
            }
            // 然后插入数据
            examDao.batchInsertQuestionTags(questionTagDOList);
        }
    }
}
